import * as vscode from 'vscode';
import { Pet } from './Pet';

/**
 * 监听用户编码活动
 */
export class ActivityMonitor {
    private pet: Pet;
    private timer?: NodeJS.Timeout;
    private lastActiveTime: number = Date.now();
    private activeThreshold = 30000; // 30秒视为有效活动

    constructor(pet: Pet) {
        this.pet = pet;
    }

    /**
     * 开始监听编辑器活动
     */
    public start() {
        // 监听文本编辑器变化
        vscode.window.onDidChangeActiveTextEditor(() => this.onActivity());
        vscode.workspace.onDidChangeTextDocument(() => this.onActivity());

        // 每分钟检查一次活动时长
        this.timer = setInterval(() => {
            const now = Date.now();
            const activeDuration = now - this.lastActiveTime;
            
            if (activeDuration >= this.activeThreshold) {
                const minutes = Math.floor(activeDuration / 60000);
                if (minutes > 0) {
                    // 确保至少累计1分钟
                    this.pet.updateCodingTime(Math.max(1, minutes));
                    this.lastActiveTime = now;
                }
            }
        }, 60000); // 每分钟检查一次
    }

    /**
     * 停止监听
     */
    public stop() {
        if (this.timer) {
            clearInterval(this.timer);
        }
    }

    /**
     * 用户活动回调
     */
    private onActivity() {
        this.lastActiveTime = Date.now();
    }
}
